package com.renrenyou.duanshipin.tools;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.renrenyou.duanshipin.R;
import com.renrenyou.duanshipin.base.BaseActivity;
import com.renrenyou.duanshipin.databinding.ActivityMd5Binding;
import com.renrenyou.duanshipin.util.FileSizeUtil;
import com.renrenyou.duanshipin.util.FileUtils;
import com.renrenyou.duanshipin.util.Md5Utils;
import com.renrenyou.duanshipin.util.ProgressDialogUtil;
import com.renrenyou.duanshipin.util.StoragePermissionHelper;
import com.renrenyou.duanshipin.util.ToastUtil;

import java.io.File;
import java.util.Random;

public class Md5Activity extends BaseActivity<ActivityMd5Binding> implements View.OnClickListener {

    private final int PICK_IMAGE_REQUEST = 1000;

    @Override
    public ActivityMd5Binding getBinding(LayoutInflater inflater) {
        return ActivityMd5Binding.inflate(inflater);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Glide.with(this).load(R.mipmap.ic_material_bg).into(mBinding.ivMd5Bg);
        mBinding.ivMd5Add.setOnClickListener(this);
        mBinding.tvMd5Change.setOnClickListener(this);
        mBinding.tvMd5ChangeAgain.setOnClickListener(this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        StoragePermissionHelper.handlePermissionResult(this, requestCode, grantResults);

        if (requestCode == StoragePermissionHelper.STORAGE_PERMISSION_REQUEST_CODE
                && grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            performFileOperations();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            Uri imageUri = data.getData();
            String filePath = imageUri.getPath();
            if (TextUtils.isEmpty(filePath)) {
                return;
            }
            Glide.with(this).setDefaultRequestOptions(new RequestOptions().frame(1000000)).load(imageUri).into(mBinding.ivMd5Pic);
            mBinding.gpMd5Add.setVisibility(View.INVISIBLE);
            mImageFilePath = FileSizeUtil.getRealPathFromUri(this, imageUri);
            mBinding.tvMd5Old.setText(Md5Utils.getFileMD5(new File(mImageFilePath)));
        }
    }

    private void performFileOperations() {
        Intent intent = new Intent(Intent.ACTION_PICK,
                MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, PICK_IMAGE_REQUEST);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.iv_md5_add) {
            if (!StoragePermissionHelper.hasStoragePermission(this)) {
                StoragePermissionHelper.requestStoragePermission(this);
            } else {
                // 已经有权限，执行文件操作
                performFileOperations();
            }
        } else if (v.getId() == R.id.tv_md5_change) {
            if (mBinding.gpMd5Add.getVisibility() == View.INVISIBLE) {
                AlertDialog dialog = ProgressDialogUtil.showProgressDialog(this);
                Handler handler = new Handler();
                handler.postDelayed(() -> {
                    dialog.dismiss();
                    Random random = new Random();
                    mBinding.tvMd5New.setText(Md5Utils.getMD5(String.valueOf(random.nextInt(100))));
                    mBinding.tvMd5ChangeAgain.setVisibility(View.VISIBLE);
                }, 5000);
            } else {
                ToastUtil.showToast(this, "请选择视频");
            }
        } else if (v.getId() == R.id.tv_md5_change_again) {
            save();
        }
    }

    private AlertDialog mProgressDialog;
    private String mImageFilePath;


    private void save() {
        String newPath = "/sdcard/Movies/" + System.currentTimeMillis() + ".mp4";

        mProgressDialog = ProgressDialogUtil.showProgressDialog(this);
        if (mThread == null) {
            mThread = new HandlerThread("saveVideo");
        }
        mThread.start();
        Handler handler = new Handler(mThread.getLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                FileUtils.copyFile(mImageFilePath, newPath);
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + newPath)));

                new Handler(Looper.getMainLooper())
                        .post(() -> {mProgressDialog.dismiss();
                            ToastUtil.showToast(Md5Activity.this,"保存成功");
                        });
            }
        };
        handler.sendEmptyMessage(100);
    }

    private HandlerThread mThread;

    @Override
    protected void onDestroy() {
        if (mThread != null) {
            mThread.quitSafely();
        }
        super.onDestroy();
    }
}
